<template>
  <view class="uni-padding-wrap uni-common-mt">
    <uni-segmented-control :current="currentTab" :values="items" :style-type="styleType" :active-color="activeColor"
      @clickItem="onClickItem" />
  </view>
  <view>
    <view v-if="currentTab === 0">
      <view v-if="currenttype == 0">
        <view>
          <view>
            <view class="title">
              <text style="font-size: 1.2em;">数据总览</text>
              <text style="margin-left: 10rpx; color: #cacdd1;">overview</text>
            </view>
            <!-- @click="open()" -->
          </view>

          <view class="search" v-if="!isMobile">
            <view>
              <uni-icons type="tune" size="20"></uni-icons>筛选
            </view>

            <uni-datetime-picker :border="true" style="flex: 2;" type="datetimerange" :end="new Date().getTime()"
              v-model="seachtime" :clearIcon="true" class="uni-stat-datetime-picker"
              :class="{ 'uni-stat__actived': currentDateTab < 0 && !!seachtime }" @change="SearchData" />

            <uni-easyinput style="flex: 3;" prefixIcon="search" trim="all" v-model="value" placeholder="请输入内容"
              @input="">
            </uni-easyinput>

            <view>
              <uni-icons type="download" size="20" @click="ExportWorlBook">导出</uni-icons>
            </view>
            <DeviceVue style="width: 200rpx;" :deviceList="deviceList" @changedevice="Changedevice"></DeviceVue>
          </view>
          <view v-if="isMobile">
            <view class="search">
              <view>
                <uni-icons type="tune" size="20"></uni-icons>筛选
              </view>
              <uni-datetime-picker :border="true" style="flex: 1;" type="datetimerange" :end="new Date().getTime()"
                v-model="seachtime" :clearIcon="false" class="uni-stat-datetime-picker"
                :class="{ 'uni-stat__actived': currentDateTab < 0 && !!seachtime }" @change="SearchData" />
            </view>
            <view class="search">
              <view>
                <uni-icons type="download" size="20" @click="ExportWorlBook">导出</uni-icons>
              </view>
              <DeviceVue style="flex: 2;" :deviceList="deviceList" @changedevice="Changedevice"></DeviceVue>
              <uni-easyinput style="flex: 3;" prefixIcon="search" trim="all" v-model="value" placeholder="请输入内容"
                @input="">
              </uni-easyinput>
            </view>
          </view>
        </view>
        <br>
        <uni-table style="max-height: 500px ;border-top:2px solid;border-bottom:2px solid;border-color: #ebeef5;"
          ref="table" :loading="loading" type="" emptyText="暂无更多数据">
          <uni-tr>
            <uni-th :width="isMobile ? 140 : 50" align="center">机房编号</uni-th>
            <uni-th width="80" v-for="(item, index) in headtitle" :key="index" align="center">
              {{ item.f_name }}
            </uni-th>
            <uni-th :width="isMobile ? 200 : 50" align="center">时间</uni-th>
          </uni-tr>
          <uni-tr v-for="(item, index) in History_data" :key="index">
            <uni-td align="center">{{ item.d_no }}</uni-td>
            <uni-td align="center">{{ item.field1 }}</uni-td>
            <uni-td align="center">{{ item.field2 }}</uni-td>
            <uni-td align="center">{{ item.field3 }}</uni-td>
            <uni-td align="center">{{ item.field4 }}</uni-td>
            <uni-td align="center">
              <view style="width: 1px;height: 10px;"></view>{{ item.c_time }}
            </uni-td>
          </uni-tr>
        </uni-table>

        <uni-pagination style="border-radius: 0px 0px 10px 10px;" :show-icon="true" :current="current"
          :total="tabletotal" @change="PageChange" />
      </view>

      <view v-show="currenttype == 0" class="echarts">
        <EchartsVue ref="EchartsRef" :headtitle="headtitle" :chartdate="Data"></EchartsVue>
      </view>

      <view v-show="currenttype == 1" class="echarts">
        <EchartsVue ref="EchartsbarRef" :headtitle="headtitle" :chartdate="Data"></EchartsVue>
      </view>
    </view>
    <view v-if="currentTab === 1">
      <view class="imageAynis">
        <view>
          <view style="display: flex; justify-content: space-between;">
            <text style="font-size: 1.2em;">
              图像识别 & 报警
            </text>
            <view style="width:25px;font-size: 1em;">
              <uni-icons color="rgb(109,114,127)" type="more-filled" size="20"></uni-icons>
            </view>
          </view>
          <view style="display:flex;align-items: center;justify-content: space-between;margin-top: 30rpx;">
            <uni-datetime-picker style="max-width: 280rpx;" :border="false" type="date" :clear-icon="true"
              v-model="single" @change="selectYoloresult" />

            <view style="color: rgb(109,114,127);font-size: 1em;">
              当前目标：人
            </view>
          </view>
        </view>
      </view>
      <view class="IndentifyItem">
        <IndentifyItemVue style="margin-top: 5px;" v-for="(item, index) in Scene" :key="index" :YoloList="item"
          Cheked="checkbox-filled"></IndentifyItemVue>
      </view>
      <uni-pagination style="border-radius: 0px 0px 10px 10px;margin-top: 30rpx;" :show-icon="true" :current="yoloPagecurrent"
        :total="yoloTableTotal" @change="yoloPageChange" /> 
    </view>
  </view>


  <!-- <view class="grid">
    <view class="content">
    </view>
  </view> -->
</template>
<script>
import ExcelJS from 'exceljs';
import ChartsVue from '@/components/functions/Charts.vue';
import DeviceVue from '@/components/functions/Device.vue';
import IndentifyItemVue from '@/components/functions/IndentifyItem.vue';
import EchartsVue from '@/components/functions/Echarts.vue';
// import { nextTick } from 'process';
import { useDeviceDetection } from '@/hooks/useDeviceDetection';
export default {
  components: {
    ChartsVue,
    DeviceVue,
    EchartsVue,
    IndentifyItemVue
  },
  data() {
    return {
      // isMobile: false, // 不再需要这个数据属性
      yoloPagecurrent:0,
      chartData: {},
      ws: null,
      Data: [
        [],
        [],
        [],
        []
      ],
      id: null,
      deviceList: [],
      Scene: [],
      History_data: [],
      History_data_compelete: [],
      History_data_compelete_tag: [],
      History_data_compelete_time: [],
      selectYolortime: null,
      tabletotal: 0,
      yoloTableTotal:0,
      sencetotal: 0,
      currentDateTab: 1,
      loading: false,
      seachtime: ['', ''],
      timecurrent: 3,
      times: ['今天', '最近一周', '最近30天', '所有'],
      // items: ['柱状图', '条形图'],
      items1: ['数据统计', '数据比较', '识别结果'],
      styleType: 'button',
      current: 0,
      currenttype: 0,
      headtitle: [],
      pagecurrent: 0,
      multipleValue: [0, 1],
      range: [{
        "value": 0,
        "text": "设备1",
      }, {
        "value": 1,
        "text": "设备2",
      }, {
        "value": 2,
        "text": "设备3"
      }],
      datatagmultipleValue: [0],
      datatagrange: [{
        "value": 0,
        "text": "温度",
      }, {
        "value": 1,
        "text": "水位",
      }, {
        "value": 2,
        "text": "烟雾"
      }],
      items: ['机房数据', '图像识别&报警'],
      currentTab:0,
      activeColor: '#007aff',
      echartData:{}
    }
  },
  setup() {
    const { isMobile } = useDeviceDetection();
    return { isMobile };
  },
  created() {
    // uni.hideTabBar({});
    this.ws = uni.connectSocket({
      // url: 'ws://localhost:8080/HistoryData',
      url: 'ws://192.168.1.111:8080/HistoryData',
      success: () => {
        console.log('WebSocket连接成功');
      }
    });
    this.ws.onMessage((e) => {
      let obj = JSON.parse(e.data);
      console.log(obj,'historyData')
      switch (obj.topic) {
        case 'device':
          obj.data.forEach((item) => {
            this.deviceList.push({
              value: item.id,
              text: item.device_name,
            });
          });
          break;
        case 'sence':
          this.Scene = obj.data
          console.log(this.Scene,'Scene');
          break;
        case 'yolo':
          this.Scene = obj.data
          break;
        case 'yolo_count':
          this.yoloTableTotal = obj.data[0].count
          break;
        case 'headtitle':
          this.headtitle = obj.data;
          this.$nextTick(() => {
            this.$refs.EchartsRef.updatecharts(obj.data)
          })
          this.echartData = obj.data
          break;
        case 't_data':
          this.History_data = obj.data
          this.Data = [
            [],
            [],
            [],
            [],
            [],
            [],
            [],
            [],
            [],
            [],
            [],
            []
          ]
          for (let i = obj.data.length-1; i >=0; i--) {
            this.Data[0].push(obj.data[i].field1)
            this.Data[1].push(obj.data[i].field2)
            this.Data[2].push(obj.data[i].field3)
            this.Data[3].push(obj.data[i].field4)
            this.Data[11].push(obj.data[i].c_time)
          }
         this.$nextTick(()=>{
           this.$refs.EchartsRef.updatecharts(obj.data)
         })

          //this.$refs.ChartsVueRef.updateData();
          break;
        case 't_data_count':
          this.tabletotal = obj.data[0].count;
          break;
        case 'sence_count':
          this.sencetotal = obj.data[0].count;
          console.log(sencetotal.value)
          break;
        case 't_data_compelete':
          this.History_data_compelete = obj.data;
          this.History_data_compelete_time = [];
          for (let i = 0; i < obj.data.length; i++) {
            this.History_data_compelete_time.push(obj.data[i].c_time)
          }
          this.$nextTick(() => {
            this.$refs.DataEchartsRef.updatacompeletecharts(this
              .History_data_compelete_time, this.History_data_compelete_tag)
          })
          break;
        default:
          break;
      }
    });
    this.ws.onClose(() => {
      console.log('WebSocket已关闭');
    });

  },
  beforeDestroy() {
    console.log('组件销毁');
    this.ws.close();
  },
  mounted() { 
    // this.isMobile = isMobile.value;
    // console.log(this.isMobile,'isMobile');
  },
  methods: {
    onClickItem(e) {
      if (this.currentTab !== e.currentIndex) {
        this.currentTab = e.currentIndex
        if (this.currentTab === 0) {
          this.$nextTick(()=>{
            this.$refs.EchartsRef.updatecharts(this.echartData)
            console.log(this.echartData,'this.echartData');
          })
        }
      }
      
    },
    styleChange(e) {
      if (this.styleType !== e.detail.value) {
        this.styleType = e.detail.value
      }
    },
    colorChange(e) {
      if (this.styleType !== e.detail.value) {
        console.log(e.detail.value);
        this.activeColor = e.detail.value
      }
    },
    SendDate(page,type) {
      let st = this.seachtime[0];
      let ed = this.seachtime[1];
      if (st === '' || st == undefined) {
        st = "1970-01-01";
      }
      if (ed === '' || ed == undefined) {
        ed = "2032-01-01";
      }
        switch(type){
          case 'room':
            this.ws.send({
              data: JSON.stringify({
                pageIndex: page,
                type: "Page",
                startDate: st + ' 00:00',
                endDate: ed + ' 23:59',
                id: this.id
              })
            });
            break;
           case 'yolo':
            this.ws.send({
              data: JSON.stringify({
                pageIndex: page,
                type: "yoloPage",
              })
            }); 
            break;
        }
    },
    changetabs(e) {
      this.current = e.currentIndex;
      console.log(this.current)
    },
    PageChange(e) {
      this.pagecurrent = e.current;
      this.SendDate((this.pagecurrent - 1) * 10,'room');
    },
    yoloPageChange(e){
      this.yoloPagecurrent = e.current;
      this.SendDate((this.yoloPagecurrent - 1) * 10,'yolo');
    },
    Changetimetabs(e) {
      this.timecurrent = e.currentIndex;
      //今天
      if (e.currentIndex == 0) {
        this.seachtime = [new Date().toLocaleDateString(), new Date().toLocaleDateString()];
      }
      //最近一周
      else if (e.currentIndex == 1) {
        let date = new Date();
        let se = new Date(date.getTime() - 7 * 24 * 60 * 60 * 1000);
        this.seachtime = [se.toLocaleDateString(), date.toLocaleDateString()];
      }
      //最近30天
      else if (e.currentIndex == 2) {
        let date = new Date();
        let se = new Date(date.getTime() - 30 * 24 * 60 * 60 * 1000);
        this.seachtime = [se.toLocaleDateString(), date.toLocaleDateString()];
      }

      //所有
      else if (e.currentIndex == 4) {
        this.seachtime = ['', ''];
      }
      this.SearchData();
    },
    SearchData(e) {
      // console.log(e,'time123');
      if(!e.length){
        this.seachtime = [];
      }
      this.pagecurrent = 0;
      this.SendDate(this.pagecurrent,'room');
    },
    Changedevice(e) {
      console.log(e,'device12312');
      
      this.pagecurrent = 0;
      this.id = e
      this.SendDate(this.pagecurrent,'room');
    },
    ExportWorlBook() {
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet('Sheet 1'); // 创建一个工作表

      // 设置列标题
      worksheet.columns = [{
        header: '机房编号',
        key: 'd_no',
        width: 20
      },
      {
        header: '温度',
        key: 'field1',
        width: 10
      },
      {
        header: '湿度',
        key: 'field2',
        width: 10
      },
      {
        header: '水位',
        key: 'field3',
        width: 10
      },
      {
        header: '时间',
        key: 'c_time',
        width: 30
      }
      ];

      worksheet.addRows(this.History_data); // 添加数据行

      // 创建一个 Blob 并下载文件
      workbook.xlsx.writeBuffer().then((buffer) => {
        const blob = new Blob([buffer], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'example.xlsx';
        link.click(); // 模拟点击下载文件
      });

    },
  
    selectYoloresult(e) {
      console.log(e,'time123123');
      
      this.selectYolortime = e;
      this.ws.send({
        data: JSON.stringify({
          type: "Yolo",
          time: this.selectYolortime,
          id: this.id
        })
      });
    },
    updata() {

      this.currenttype = this.currenttype == 1 ? 0 : 1;

      this.$nextTick(() => {
        this.$refs.EchartsbarRef.updatabarcharts(this.headtitle, true)
      })
    },
    onchangeMultiple() {
      let head = [];
      for (let i = 0; i < this.datatagmultipleValue.length; i++) {
        for (let j = 0; j < this.multipleValue.length; j++) {
          console.log(this.datatagrange[i].text)
          console.log(this.range[j].text)
          head.push({
            "f_name": this.range[j].text + this.datatagrange[i].text
          })
          this.History_data_compelete_tag = head
        }
      }
    }
  }
}
</script>


<style scoped>
.grid{
  display: flex;
  justify-content: center;
  padding: 20rpx;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, SimSun, sans-serif;
}
.content{
  width: 100%;
}
.title{
  margin-top: 30rpx;
}
.search{
  /* width: 100%; */
  margin-top: 30rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
}
.echarts{
    margin-top: 50rpx;
    background-color: white;
    width: 100%;
    height: 50vh;
    border-radius: 10px;
    border: 2px solid;
    border-color: rgb(230, 231, 235);
}

.item-selected {
  background-color: #007aff;
  color: #fff;
}

.item-disabled {
  background-color: #f5f5f5;
  color: #999;
  opacity: 0.6;
}

.item-disabled.item-selected {
  background-color: #d0d0d0;
  color: #666;
}


.imageAynis {
  margin-top: 30rpx;
     height: 100px;
     padding: 30rpx;
     background-color: white;
    border-radius: 10px;
    border: 2px solid;
    border-color: rgb(230, 231, 235);
}

.IndentifyItem{
  width: 100%;
  display: grid;
  grid-template-columns: repeat(2, minmax(150rpx, auto));
  gap: 20rpx;
}

/* 移动端适配 - 针对小屏幕优化 */
@media screen and (max-width: 415px) {
.echarts {
    height: 500rpx;
    width: 1500rpx;
    /* 用 scale 整体缩放后，强制还原高度 */
    transform: scale(0.47) scaleY(2);
    transform-origin: left top;
    /* background-color: pink;  */
  }

  .IndentifyItem{
      grid-template-columns: repeat(1, minmax(150rpx, auto));
  }
}


@media screen and (min-width: 416px) and (max-width:716px) {
.echarts {
    height: 500rpx;
    width: 1500rpx;
    /* 用 scale 整体缩放后，强制还原高度 */
    transform: scale(0.47) scaleY(2);
    transform-origin: left top;
    /* background-color: pink;  */
  }
        .IndentifyItem {
          grid-template-columns: repeat(1, minmax(150rpx, auto));
        }
}


@media screen and (min-width:717px) and (max-width:1023px) {
 
}


@media screen and (min-width: 1024px) {
  
}


</style>